<template>
  <div class="equipment-management">
    <!-- 页眉 -->
    <el-row class="page-header">
      <el-col :span="24" class="header-container">
        <div class="page-title">组织机构 - 设施设备</div>
        <div class="user-actions">
          <el-button type="success" icon="plus" @click="handleAddEquipment">添加设备</el-button>
          <el-button @click="handleManagementClick">管理规程</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索框 -->
    <el-col :span="24" class="search-container">
      <el-input
        v-model="searchText"
        placeholder="搜索设备..."
        class="search-input"
        suffix-icon="el-icon-search"
        clearable
      />
    </el-col>
    <!-- 设备表格 -->
    <el-row>
      <el-col :span="24">
        <el-table :data="filteredEquipmentList" border class="custom-table" style="width: 100%">
          <el-table-column
            prop="devicenumber"
            label="设备编号"
            width="120"
            class-name="custom-header"
          />
          <el-table-column prop="devicename" label="设备名称" class-name="custom-header" />
          <el-table-column prop="model" label="型号" class-name="custom-header" />
          <el-table-column prop="manufacturer" label="制造商" class-name="custom-header" />
          <el-table-column prop="status" label="状态" width="120" class-name="custom-header">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? "正常" : "停用" }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150" class-name="custom-header">
            <template #default="{ row }">
              <div class="button-container">
                <el-button
                  link
                  size="small"
                  icon="view"
                  class="custom-button"
                  @click="handleViewEquipment(row)"
                />
                <el-button
                  link
                  size="small"
                  icon="edit"
                  class="custom-button"
                  @click="handleEditEquipment(row)"
                />
                <el-button
                  link
                  size="small"
                  icon="delete"
                  class="custom-button"
                  @click="handleDeleteConfirmation(row)"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 添加/查看设备弹窗 -->
    <el-dialog
      v-model="addEquipmentDialogVisible"
      :title="isViewMode ? '查看设备' : isEditMode ? '编辑设备' : '添加设备'"
      width="50%"
    >
      <el-form ref="addFormRef" :model="addForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="设备编号"
              prop="devicenumber"
              :rules="[{ required: true, message: '设备编号不能为空', trigger: 'blur' }]"
            >
              <el-input
                v-model="addForm.devicenumber"
                :disabled="isViewMode"
                placeholder="请输入设备编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号">
              <el-input v-model="addForm.model" :disabled="isViewMode" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称">
              <el-input
                v-model="addForm.devicename"
                :disabled="isViewMode"
                placeholder="请输入设备名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购日期">
              <el-date-picker
                v-model="addForm.purchaseDate"
                type="date"
                :disabled="isViewMode"
                placeholder="选择采购日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="制造商">
              <el-input
                v-model="addForm.manufacturer"
                :disabled="isViewMode"
                placeholder="请输入制造商"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用日期">
              <el-date-picker
                v-model="addForm.startDate"
                type="date"
                :disabled="isViewMode"
                placeholder="选择启用日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存放位置">
              <el-input
                v-model="addForm.location"
                :disabled="isViewMode"
                placeholder="请输入存放位置"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 添加设备状态滑动开关 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备状态">
              <el-switch
                v-model="addForm.status"
                :active-value="1"
                :inactive-value="0"
                :disabled="isViewMode"
                active-text="正常"
                inactive-text="停用"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="addEquipmentDialogVisible = false">关闭</el-button>
        <el-button v-if="!isViewMode && !isEditMode" type="primary" @click="validateForm">
          添加
        </el-button>
        <el-button v-if="!isViewMode && isEditMode" type="primary" @click="handleUpdateEquipment">
          保存编辑
        </el-button>
      </template>
    </el-dialog>

    <!-- 管理规程对话框 -->
    <el-dialog v-model="dialogVisible" title="管理规程">
      <el-button type="primary" @click="handleAddManagement">新增</el-button>
      <el-table :data="tableData" border>
        <el-table-column prop="eqtype" label="文件类型" width="120" />
        <el-table-column prop="eqname" label="名称" min-width="150" />
        <el-table-column prop="eqnumber" label="编号" width="230" />
        <el-table-column prop="picUrl" label="图片" width="150" >
          <template #default="{ row }">
            <div v-if="row.picUrl">
              <div v-for="item in row.picUrl.split(',')" v-key="item">
                <img :src="item" alt="" style="width: 100px; height: 100px" />
              </div>
            </div>
            <template v-else>暂无图片</template>
          </template>
        </el-table-column>
        <el-table-column prop="fileName" label="文件" width="150" />
        <el-table-column prop="addtime" label="添加日期" width="150" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              link
              size="small"
              class="custom-button"
              @click="handleDeleteManagementConfirmation(row)"
            >
              删除
            </el-button>
            <el-button
              link
              size="small"
              class="custom-button"
              icon="view"
              @click="proviewFile(row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增管理规程弹窗 -->
    <el-dialog v-model="innerDialogVisible" title="新增管理规程" width="30%">
      <el-form ref="formRef" :model="form" label-width="80px" :rules="formRules">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.eqtype">
            <el-radio label="SMP">SMP</el-radio>
            <el-radio label="SOP">SOP</el-radio>
            <el-radio label="SOR">SOR</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="eqname">
          <el-input v-model="form.eqname" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="编号" prop="eqnumber">
          <el-input v-model="form.eqnumber" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="文件" prop="fileUrl">
          <FileUpload v-model="fileUrls" accept="application/pdf" accept-name="pdf" style="width:auto;float:left" :limit="1" @change="handleFileChange" />
        </el-form-item>
        <el-form-item label="图片" prop="picUrl">
          <MultiImageUpload v-model="picUrls" :limit="10" @change="handleImageChange" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="innerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmitManagement">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import request from "@/utils/request";
import type { FormInstance, FormRules } from "element-plus";


// 设备数据和操作
interface Equipment {
  id?: string;
  devicename: string;
  devicenumber: string;
  model: string;
  manufacturer: string;
  status: string;
  usagetime: string;
  ustime: string;
  purchaseDate?: string;
  startDate?: string;
  location?: string;
}

const equipmentList = ref<Equipment[]>([]);
const searchText = ref<string>("");
const addEquipmentDialogVisible = ref<boolean>(false);
const isViewMode = ref<boolean>(false);
const isEditMode = ref<boolean>(false); // 新增编辑模式标识
const addForm = ref<Equipment>({
  devicenumber: "",
  devicename: "",
  model: "",
  manufacturer: "",
  status: "正常",
  usagetime: "",
  ustime: "",
  location: "",
});

const picUrls = ref<[]>([]);
const fileUrls = ref<[]>([]);

const handleAddEquipment = () => {
  isViewMode.value = false;
  isEditMode.value = false;
  addEquipmentDialogVisible.value = true;
  Object.keys(addForm.value).forEach((key) => (addForm.value[key] = undefined));
};

const getList = async () => {
  const res = await request({
    url: "/api/v1/device/all",
    method: "post",
    params: {
      keyword: searchText.value,
    },
  });
  equipmentList.value = res;
  filteredEquipmentList.value = res;
};

const addFormRef = ref<FormInstance>();
const validateForm = () => {
  if (!addFormRef.value) return;
  addFormRef.value.validate((valid: boolean) => {
    if (valid) {
      handleAddSubmitEquipment();
    }
  });
};

const handleAddSubmitEquipment = async () => {
  const dataToSend = {
    devicenumber: addForm.value.devicenumber,
    devicename: addForm.value.devicename,
    model: addForm.value.model,
    manufacturer: addForm.value.manufacturer,
    status: addForm.value.status,
    purchaseDate: addForm.value.purchaseDate,
    startDate: addForm.value.startDate,
    usagetime: addForm.value.usagetime,
    ustime: addForm.value.ustime,
    location: addForm.value.location,
    id: addForm.value.id,
  };
  await request({
    url: "/api/v1/device/dev",
    method: "post",
    data: dataToSend,
  });
  ElMessage.success("设备添加成功");
  addEquipmentDialogVisible.value = false;
  getList();
};
/**
 * 编辑按钮
 */
const handleEditEquipment = (row: Equipment) => {
  isViewMode.value = false;
  isEditMode.value = true;
  addEquipmentDialogVisible.value = true;
  Object.assign(addForm.value, row);
};

const handleUpdateEquipment = async () => {
  const dataToSend = {
    devicenumber: addForm.value.devicenumber,
    devicename: addForm.value.devicename,
    model: addForm.value.model,
    manufacturer: addForm.value.manufacturer,
    status: addForm.value.status,
    purchaseDate: addForm.value.purchaseDate,
    startDate: addForm.value.startDate,
    location: addForm.value.location,
    id: addForm.value.id,
  };
  await request({
    url: "/api/v1/device/upd",
    method: "put",
    data: dataToSend,
  });
  ElMessage.success("设备编辑成功");
  addEquipmentDialogVisible.value = false;
  isEditMode.value = false;
  getList();
};

const handleViewEquipment = (row: Equipment) => {
  isViewMode.value = true;
  addEquipmentDialogVisible.value = true;
  Object.assign(addForm.value, row);
};

const handleDeleteConfirmation = async (row: any) => {
  try {
    const res = await request({
      url: "/api/v1/device/" + row.id,
      method: "delete",
    });
    console.log("设备删除成功", res);
    getList(); // 更新设备列表
  } catch (error) {
    console.error("设备删除失败:", error);
  }
};


const filteredEquipmentList = computed(() => {
  return equipmentList.value.filter(
    (item) =>
      item.devicenumber.includes(searchText.value) ||
      item.devicename.includes(searchText.value) ||
      item.model.includes(searchText.value) ||
      item.manufacturer.includes(searchText.value)
  );
});

// 管理规程数据和操作
const dialogVisible = ref(false);
const innerDialogVisible = ref(false);
const form = reactive({
  eqtype: "",
  eqname: "",
  eqnumber: "",
  fileUrl: "",
  fileName:undefined,
  picUrl:undefined
});
const handleFileChange =(files: any)=>{
  if(files.length === 0) {
    form.fileUrl = undefined;
    form.fileName = undefined;
  }else{
    
  form.fileUrl = files[0].url;
  form.fileName = files[0].name;
  
}
}
const handleImageChange =(files: any)=>{
  if(files.length === 0) {
    form.picUrl = undefined;
  }else{
    let picPaths =  "";
    files.forEach((path: any) => {  
      picPaths += path + ",";
    });
    if(picPaths == ""){
       form.picUrl = undefined;
       return ;
    }
    form.picUrl = picPaths.substring(0, picPaths.length - 1);
  }
}
const formRef = ref<FormInstance>();
const formRules: FormRules = {
  eqtype: [{ required: true, message: "请选择类型", trigger: "change" }],
  eqname: [{ required: true, message: "请输入名称", trigger: "blur" }],
  eqnumber: [{ required: true, message: "请输入编号", trigger: "blur" }],
  fileUrl: [{ required: true, message: "请输入文件名", trigger: "change" }],
};

const tableData = ref([
  // { fileType: "SMP", name: "安全生产规程", number: "001", addDate: "2024-01-01" },
  // { fileType: "SOP", name: "设备操作规程", number: "002", addDate: "2024-01-02" },
]);

const handleManagementClick = () => {
  dialogVisible.value = true;
  getManagementProcedures();
};

const handleAddManagement = () => {
  Object.keys(form).forEach((key) => (form[key] = ""));
  //formRef.value?.resetFields();
  fileUrls.value = [];
  picUrls.value = [];
  innerDialogVisible.value = true;
};
const handleAddSubmitManagement = async () => {
  formRef.value
    ?.validate()
    .then(async () => {
      try {
        await request({
          url: "/api/v1/equipment/save",
          method: "post",
          data: {
            ...form,
            addDate: new Date().toISOString().split("T")[0],
          },
        });
        innerDialogVisible.value = false;
        ElMessage.success("新增管理规程成功！");
        getManagementProcedures(); // 刷新管理规程列表
      } catch (error) {
        console.error("新增管理规程失败：", error);
        ElMessage.error("新增管理规程失败");
      }
    })
    .catch((error) => {
      console.error("表单验证失败：", error);
    });
};
const getManagementProcedures = async () => {
  try {
    const res = await request({
      url: "/api/v1/equipment/all",
      method: "POST",
    });
    tableData.value = res; // 假设返回的数据可以直接赋值给 tableData
  } catch (error) {
    console.error("获取管理规程失败:", error);
    ElMessage.error("获取管理规程失败");
  }
};

// 在组件挂载后调用
onMounted(() => {
  getList(); // 获取设备列表
  //getManagementProcedures(); // 获取管理规程列表
});
// const handleAddSubmitManagement = () => {
//   formRef.value
//     ?.validate()
//     .then(() => {
//       tableData.value.push({
//         ...form,
//         addDate: new Date().toISOString().split("T")[0],
//       });
//       innerDialogVisible.value = false;
//       ElMessage.success("新增管理规程成功！");
//     })
//     .catch((error) => {
//       console.error("表单验证失败：", error);
//     });
// };
const handleDeleteManagementConfirmation = async (row: any) => {
  ElMessageBox.confirm("确定要删除此管理规程吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await request({
          url: `/api/v1/equipment/${row.id}`,
          method: "delete",
        });
        const index = tableData.value.indexOf(row);
        if (index !== -1) {
          tableData.value.splice(index, 1);
          ElMessage.success("删除成功");
        }
      } catch (error) {
        console.error("删除管理规程失败:", error);
        ElMessage.error("删除管理规程失败");
      }
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};

const proviewFile = (row:any)=>{
  window.open(row.fileUrl);
}
// const handleDeleteManagementConfirmation = (row: any) => {
//   ElMessageBox.confirm("确定要删除此管理规程吗？", "提示", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   })
//     .then(() => {
//       const index = tableData.value.indexOf(row);
//       if (index !== -1) {
//         tableData.value.splice(index, 1);
//         ElMessage.success("删除成功");
//       }
//     })
//     .catch(() => {
//       ElMessage.info("取消删除");
//     });
// };

// 文件上传功能（示例，需根据实际情况完善逻辑）
const handleFileUpload = async (file: File) => {
  const formData = new FormData();
  formData.append("file", file);
  await request({
    url: "/api/v1/files",
    method: "post",
    data: formData,
  });
  ElMessage.success("文件上传成功");
};

// 根据设备编号修改设备状态功能
const changeDeviceStatus = async (deviceNumber: string, newStatus: string) => {
  await request({
    url: `/api/v1/device/${deviceNumber}/status`,
    method: "post",
    data: { status: newStatus },
  });
  ElMessage.success("设备状态修改成功");
  getList();
};

// 删除设备功能（使用给定的删除接口）
const handleDeleteDeviceById = async (id: string) => {
  await request({
    url: `/api/v1/device/${id}`,
    method: "delete",
  });
  ElMessage.success("设备删除成功");
  getList();
};
</script>
<style scoped>
.equipment-management {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-title {
  font-size: 20px;
  font-weight: bold;
  color: #4caf50;
}
.search-container {
  margin-bottom: 20px;
}
.search-input {
  width: 300px;
}
.el-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}
.custom-button {
  background-color: transparent;
  border: none;
  color: inherit;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
